<template>
  <div>
    <Header title="社会组织申请" :back="true" />
    <div class="box">
      <a-form-model
        ref="form"
        :model="form"
        :rules="rules"
        :label-col="{ span: 8 }"
        :wrapper-col="{ span: 10 }"
      >
        <a-form-model-item label="组织名称" prop="organizationName">
          <a-input v-model="form.organizationName" disabled />
        </a-form-model-item>
        <a-form-model-item label="社会组织类型" prop="socialOrganizationTypeId">
          <a-select v-model="form.socialOrganizationTypeId">
            <a-select-option value="">请选择</a-select-option>
            <a-select-option
              v-for="item in typeList"
              :key="item.id"
              :value="item.id"
              >{{ item.type }}</a-select-option
            >
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="图片上传" prop="fileId">
          <a-upload
            accept=".jpg, .jpeg, .png, .JPG, .JPEG, .PNG"
            :action="uploadUrl"
            :file-list="fileList"
            :headers="headers"
            :beforeUpload="beforeUpload"
            :remove="fileRemove"
            @change="fileChange"
          >
            <a-button
              :disabled="fileList.length > fileLimit - 1 ? true : false"
            >
              <a-icon type="upload" /> Upload
            </a-button>
          </a-upload>
          <span class="upload_text">(请上传社会组织章程第一章)</span>
        </a-form-model-item>
        <a-form-model-item label="申报级别" prop="declarationLevelId">
          <a-radio-group v-model="form.declarationLevelId">
            <a-radio v-for="item in levelList" :key="item.id" :value="item.id">
              {{ item.level }}
            </a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item label="业务主管单位" prop="unitInfoId">
          <a-select v-model="form.unitInfoId">
            <a-select-option value="">请选择</a-select-option>
            <a-select-option
              v-for="item in unitList"
              :key="item.id"
              :value="item.id"
              >{{ item.name }}</a-select-option
            >
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="法定代表人" prop="legalPerson">
          <a-input v-model="form.legalPerson" />
        </a-form-model-item>
        <a-form-model-item label="法定代表人电话" prop="phone">
          <a-input v-model="form.phone" :max-length="11" />
        </a-form-model-item>
        <a-form-model-item label="承诺书" prop="isChecked">
          <a-checkbox-group v-model="form.isChecked" @change="checkBoxClick">
            <a-checkbox value="1" />
          </a-checkbox-group>
          <span class="text">
            我已阅读并同意填写
            <span @click="showModal">承诺书</span>
          </span>
        </a-form-model-item>
        <a-form-model-item :wrapper-col="{ span: 3, offset: 12 }">
          <a-button type="primary" @click="nextStep">提交审核</a-button>
        </a-form-model-item>
      </a-form-model>
    </div>
    <a-modal
      :visible="visible"
      title="承诺书"
      :body-style="{ padding: '24px 40px' }"
      :width="800"
      centered
      :footer="null"
      @cancel="visible = false"
    >
      <div class="home">
        <!-- <div ref="file"></div> -->
        <div class="file" v-html="fileHtml"></div>
      </div>
      <!-- 手写签名 -->
      <div class="sign-box">
        <vue-esign
          ref="esign"
          :width="800"
          :height="300"
          :isCrop="isCrop"
          :lineWidth="lineWidth"
          :lineColor="lineColor"
          :bgColor.sync="bgColor"
        />
      </div>
      <div class="btn-group">
        <a-button type="primary" @click="createSign">确认</a-button>
        <a-button type="danger" @click="resetSign">重绘</a-button>
      </div>
    </a-modal>
  </div>
</template>
<script>
import vueEsign from "vue-esign";
import {
  uploadFile,
  levelList,
  socialOrganizationTypeList,
  unitInfoList,
} from "@/api";
import {
  declarationInfo,
  getCommitmentLetter,
  declarationSystem,
  getDeclarationLevels,
  getOrganizationTypes,
  getDeclarationInfo,
  getSignCommitmentLetter,
} from "@/api/entry";
import Header from "@/components/header.vue";
const RegPhone = /^1[3456789]\d{9}$/;
import axios from "axios";
const docx = require("docx-preview");
import { baseApi } from '@/config'
export default {
  name: "entry",
  components: { vueEsign, Header },
  data() {
    const validatePhone = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入法定代表人电话"));
      } else if (!RegPhone.test(this.form.phone)) {
        callback(new Error("请输入正确的手机号"));
      } else {
        callback();
      }
    };
    return {
      form: {
        organizationName: "",
        socialOrganizationTypeId: "", // 社会组织类型id
        unitInfoId: "", // 所属单位id
        declarationLevelId: "", // 申报级别id
        legalPerson: "", // 法人姓名
        phone: "", // 法人电话
        signatureFileId: "", // 签名图片
        fileId: "",
        isChecked: [],
        signatureImgId: "", // 签名图片id
      },
      rules: {
        organizationName: [
          { required: true, message: "请输入组织名称", trigger: "blur" },
        ],
        socialOrganizationTypeId: [
          { required: true, message: "请选择社会组织类型", trigger: "change" },
        ],
        unitInfoId: [
          { required: true, message: "请选择业务主管单位", trigger: "change" },
        ],
        declarationLevelId: [
          { required: true, message: "请选择申报级别", trigger: "change" },
        ],
        legalPerson: [
          { required: true, message: "请输入法定代表人", trigger: "blur" },
        ],
        phone: [{ required: true, validator: validatePhone, trigger: "blur" }],
        isChecked: [
          {
            type: "array",
            required: true,
            message: "请勾选承诺书",
            trigger: "change",
          },
        ],
        fileId: [{ required: true, message: "请上传图片", trigger: "change" }],
      },
      visible: false,
      lineWidth: 6,
      lineColor: "#000000",
      bgColor: "",
      isCrop: false,
      declareSystemId: "",
      levelList: [], // 申报级别列表
      referLevelIds: [],
      typeList: [], // 组织类别列表
      referTypeIds: [],
      unitList: [], // 业务主管单位列表
      commitmentLetterUrl: "", // 承诺书
      fileHtml: "",
      uploadUrl: `${baseApi}/minio/uploadFile`,
      fileLimit: 1,
      headers: {},
      fileList: [],
      requestType: "",
    };
  },
  methods: {
    checkBoxClick() {
      if (this.form.isChecked.length) {
        this.visible = true;
      }
    },
    nextStep() {
      const _ts = this;
      if (!_ts.form.signatureFileId) {
        _ts.$message.error("请填写承诺书");
        return false;
      }
      // console.log(this.fileList);
      // console.log(_ts.form);
      _ts.$refs.form.validate((valid) => {
        if (valid) {
          let params = {},
            method = "";
          if (_ts.requestType === "add") {
            params = _ts.form;
            method = "post";
          } else if (_ts.requestType === "edit") {
            params = {
              ..._ts.form,
              id: _ts.$storejs.get("enterInfo").id,
              status: 1,
            };
            method = "put";
          }
          declarationInfo(params, method).then((res) => {
            if (res.data) {
              _ts.$storejs.set("enterInfo", {
                ...res.data,
                declarationInfoId: res.data.id,
              });
            }
            _ts.$message.success({
              content: "提交成功，请静待审核",
              duration: 1.2,
            });
            setTimeout(() => {
              _ts.$router.push("/home");
            }, 1200);
          });
        }
      });
    },
    showModal() {
      const _ts = this;
      _ts.visible = true;

      // axios({
      //   method: "get",
      //   responseType: "blob", // 设置响应文件格式
      //   url: _ts.commitmentLetterUrl,
      //   // url: "https://hkrl.wincrosoft.net/hkrl-minio/7494ce30a97742859202b0e4ffbe26b4.docx",
      // }).then(({ data }) => {
      //   docx.renderAsync(data, _ts.$refs.file); // 渲染到页面预览
      // });
    },
    base642File(base64) {
      // Blob
      const arr = base64.split(",");
      const mime = arr[0].match(/:(.*?);/)[1];
      const bstr = atob(arr[1]);
      let n = bstr.length;
      const u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], { type: mime });
    },
    base64toFile(dataurl, filename = "file") {
      // Binary
      let arr = dataurl.split(",");
      let mime = arr[0].match(/:(.*?);/)[1];
      let suffix = mime.split("/")[1];
      let bstr = atob(arr[1]);
      let n = bstr.length;
      let u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      let file = new File([u8arr], `${filename}.${suffix}`, {
        type: mime,
      });
      return file;
    },
    createSign() {
      this.$refs.esign
        .generate()
        .then((res) => {
          // console.log(res);
          // console.log(this.base64toFile(res));
          this.uploadFileRequest(this.base64toFile(res));
        })
        .catch(() => {
          this.$message.error("请签名");
        });
    },
    resetSign() {
      this.$refs.esign.reset();
    },
    // 签名上传
    uploadFileRequest(file) {
      const params = new FormData();
      params.append("file", file);
      uploadFile(params).then((res) => {
        // console.log(res.data);
        getSignCommitmentLetter({
          signImgId: res.data.id,
          socialOrganizationName: this.form.organizationName,
        }).then((signRes) => {
          this.form.signatureFileId = signRes.data.id;
        });
        this.form.signatureImgId = res.data.id;
        this.visible = false;
      });
    },
    // 获取申报信息
    getDeclarationInfoRequest(id) {
      getDeclarationInfo(id).then((res) => {
        const imgUrlSplit = res.data.url.split("/");
        const imgName = imgUrlSplit[imgUrlSplit.length - 1];
        this.fileList = [
          {
            uid: 1,
            name: imgName,
            status: "done",
            url: res.data.url,
          },
        ];
        let {
          socialOrganizationTypeId,
          unitInfoId,
          declarationLevelId,
          legalPerson,
          phone,
          signatureFileId,
          fileId,
        } = res.data;
        this.form = {
          socialOrganizationTypeId,
          unitInfoId,
          declarationLevelId,
          legalPerson,
          phone,
          signatureFileId,
          fileId,
        };
        this.form.organizationName =
          this.$storejs.get("userInfo").user.userName;
        this.form.isChecked = ["1"];
      });
    },
    // 获取申报级别列表
    getLevelList() {
      // levelList({}).then((res) => {
      //   const resData = res.data;
      //   const referLevelIds = this.referLevelIds;
      //   const levelList = resData.filter(
      //     (item) => referLevelIds.indexOf(item.id) > -1
      //   );
      //   this.levelList = levelList;
      //   // this.levelList = resData;
      // });
      getDeclarationLevels({ declarationSystemId: this.declareSystemId }).then(
        (res) => {
          this.levelList = res.data;
        }
      );
    },
    // 获取组织类别列表
    getTypeList() {
      // socialOrganizationTypeList({}).then((res) => {
      //   const resData = res.data;
      //   const referTypeIds = this.referTypeIds;
      //   const typeList = resData.filter(
      //     (item) => referTypeIds.indexOf(item.id) > -1
      //   );
      //   this.typeList = typeList;
      //   // this.typeList = resData;
      // });
      getOrganizationTypes({ declarationSystemId: this.declareSystemId }).then(
        (res) => {
          this.typeList = res.data;
        }
      );
    },
    // 获取业务主管单位列表
    getUnitList() {
      unitInfoList({}).then((res) => {
        this.unitList = res.data;
      });
    },
    // 获取承诺书
    getCommitFile() {
      getCommitmentLetter({}).then((res) => {
        this.commitmentLetterUrl = res.data.commitmentLetterUrl;
        this.fileHtml = res.data.commitmentLetter;
      });
    },
    // 获取该体系下的社会组织类型及级别
    getCurrentSystemIds(id) {
      return new Promise((resolve) => {
        declarationSystem(id).then((res) => {
          this.referLevelIds = res.data.levelIds;
          this.referTypeIds = res.data.typeIds;
          resolve();
          // levelIds--申报级别, typeIds--组织类型
        });
      });
    },
    // 图片上传
    beforeUpload() {
      this.headers = {
        Authorization: this.$storejs.get("token"),
      };
    },
    fileChange({ file, fileList }) {
      this.fileList = fileList;
      if (file.status === "done") {
        // 单张，多张的话可能需要URL拼接
        // console.log(file.response.data);
        const imgType = file.response.data.type;
        if (
          imgType === "jpg" ||
          imgType === "jpeg" ||
          imgType === "png" ||
          imgType === "JPG" ||
          imgType === "JPEG" ||
          imgType === "PNG"
        ) {
          this.form.fileId = file.response.data.id;
        } else {
          this.$message.error("请上传正确格式的图片");
          this.fileRemove();
        }
      }
    },
    fileRemove() {
      this.form.fileId = "";
      this.fileList = [];
    },
  },
  created() {
    this.form.organizationName = this.$storejs.get("userInfo").user.userName;
    const declareSystemId = this.$storejs.get("declarationSystemId");
    this.declareSystemId = declareSystemId;
    if (this.$route.query.id) {
      const declareInfoId = this.$storejs.get("enterInfo").id;
      this.getDeclarationInfoRequest(declareInfoId);
      this.requestType = "edit";
    } else {
      this.requestType = "add";
    }
    this.getLevelList();
    this.getTypeList();
    // Promise.all([this.getCurrentSystemIds(declareSystemId)]).then(() => {
    //   this.getLevelList();
    //   this.getTypeList();
    // });
    this.getUnitList();
    this.getCommitFile();
  },
};
</script>
<style lang="less" scoped>
.box {
  margin-top: 3.125rem;
  .text {
    padding-left: 0.625rem;
    span {
      color: #1890ff;
      cursor: pointer;
    }
  }
  .upload_text {
    color: #ccc;
    position: absolute;
    left: 20%;
    top: -10px;
  }
}
.home {
  width: 100%;
  max-height: 600px;
  overflow-y: scroll;
}
::v-deep .docx-wrapper {
  padding: none;
  background: none;
}
::v-deep .docx {
  width: auto !important;
  padding: 0px !important;
  box-shadow: none !important;
}
.sign-box {
  border: 1px solid #e8e8e8;
}
.btn-group {
  margin-top: 20px;
  display: flex;
  align-items: center;
  justify-content: space-around;
}
</style>